# -*- coding: utf-8 -*-
# @Python：3.8
# @项目：happiness_order
# @文件：user.py
# @时间：2025/1/20 14:01
# @作者：yangzhang
# @desc:
from flask import Blueprint, jsonify, request
from common.models.user import User
from common.util.log_util import logger
from common.libs.user.user_service import UserService

route_user = Blueprint('user_api', __name__, url_prefix='/user')


@route_user.route('/list')
def user_list():
    data = {'code': '0', 'msg': 'success', 'users': []}
    users = User.query.all()
    for user in users:
        user_info = {
            'id': user.id,
            'name': user.name
        }
        data['users'].append(user_info)
    return jsonify(data)


@route_user.route('/login', methods=['POST'])
def login():
    resp_data = {'code': '0', 'msg': 'success'}
    request_data = request.get_json()
    logger.info(request_data)
    name = request_data.get('name')
    passwd = request_data.get('password')
    if name is None or passwd is None:
        resp_data['code'] = '-1'
        resp_data['msg'] = '请输入用户名或者密码'
        return jsonify(resp_data)
    user = User.query.filter(User.name == name).first()

    if not user:
        resp_data['code'] = '-2'
        resp_data['msg'] = '用户不存在'
        return jsonify(resp_data)
    if not UserService.check_pwd(passwd, hashed_pwd=user.passwd):
        resp_data['code'] = '-3'
        resp_data['msg'] = '用户名或者密码错误'
        return jsonify(resp_data)
    return jsonify(resp_data)
